﻿
using CameraClient.CForm;
using CameraClient.CForm.CameraF;
using ChargingSystem4.CsForm;
using Edge.Repository.Base;

using EMSClient.Config;

using MeetingClient;
using Oliving.Common;
using Oliving.Common.LogHelper;
using Oliving.Common.MyHelper;
using Oliving.FormCommon.Oliving.Common;
using System;
using System.IO;
using System.Threading;
using System.Windows.Forms;

namespace CameraClient
{
    static class Program
    {
        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main()
        {

            #region 捕获异常
            //处理未捕获的异常   
            Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
            //处理UI线程异常   
            Application.ThreadException += Application_ThreadException;
            //处理非UI线程异常   
            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;

            Application.ApplicationExit += OnApplicationExit;
            #endregion

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            #region 日志

            try
            {
                string myPath = Path.Combine(System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase, "log");
                DelLog.Del(myPath);
            }
            catch { }




            try
            {
                string myPathNew = Path.Combine(System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase, "html");
                DelLog.Del_html(myPathNew);
            }
            catch { }


            Thread thread = new Thread(() =>
                {
                    while (true)
                    {
                        Thread.Sleep(5 * 60 * 1000);

                        try
                        {
                            string myPath = Path.Combine(System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase, "tempImg");
                            DirectoryInfo root = new DirectoryInfo(myPath);
                            FileInfo[] files = root.GetFiles();
                            foreach (FileInfo file in files)
                            {
                                DateTime fileTime = file.CreationTime.AddMinutes(10);
                                if (fileTime < DateTime.Now)
                                {
                                    file.Delete();
                                }
                            }
                        }
                        catch { }
                    }
                });
            thread.IsBackground = true;
            thread.Start();





            #endregion


            #region 辅助

            //检测更新(此处演示网址为此控件库的更新地址)
            // FSLib.App.SimpleUpdater.Updater.CheckUpdateSimple("http://localhost:8002/client/{0}", "update_c.xml");

            #region 进度条

            try
            {
                Splasher.Show(typeof(FrmSplashBox));
                Splasher.Status = "正在初始化程序基础数据，请稍候... ...";

                // 在线更新
                // FSLib.App.SimpleUpdater.Updater.CheckUpdateSimple("http://localhost:8002/client/{0}", "update.xml");
            }
            catch { }

            #endregion


            #region 皮肤 
            //try
            //{
            //    Sunisoft.IrisSkin.SkinEngine skinEngine1 = new Sunisoft.IrisSkin.SkinEngine();
            //    skinEngine1.SkinDialogs = false;
            //    skinEngine1.SkinFile = System.AppDomain.CurrentDomain.BaseDirectory + "/Skins/mp10.ssk";
            //}
            //catch { }
            #endregion

            // KeyboardAssembly.Hook_Start();

            #region 单利模式
            string p = System.Diagnostics.Process.GetCurrentProcess().ProcessName;
            // get the list of all processes by that name
            System.Diagnostics.Process[] processes = System.Diagnostics.Process.GetProcessesByName(p);
            // if there is more than one process
            if (processes.Length > 2)
            {
                NLogger.Default.Debug("单利模式", "程序正在运行".ToString());
                //MessageBox.Show("程序正在运行或未完全关闭，请稍后再试。", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);

                Splasher.Status = "程序正在运行或未完全关闭，请稍后再试。";
                Thread.Sleep(2000);
                foreach (var pItem in processes)
                {
                    try { pItem.Kill(); } catch { }
                    try { pItem.Close(); } catch { }
                }

                Application.Exit();
            }
            else
            {

                #endregion


                EdgeSqlSugarClient.SqlSugarClient();

                #region MyRegion

                /**
            * 当前用户是管理员的时候，直接启动应用程序
            * 如果不是管理员，则使用启动对象启动程序，以确保使用管理员身份运行
            */
                //获得当前登录的Windows用户标示
                System.Security.Principal.WindowsIdentity identity = System.Security.Principal.WindowsIdentity.GetCurrent();
                System.Security.Principal.WindowsPrincipal principal = new System.Security.Principal.WindowsPrincipal(identity);



                //  ZhuCe();
                RunMain();
                //  RunMain();

                #region 删除

                if (false)
                {
                    //if (!AppConfigHelper.isTest)
                    //{
                    //    //判断当前登录用户是否为管理员
                    //    if (principal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator))
                    //    {
                    //        ZhuCe();

                    //    }
                    //    else
                    //    {
                    //        //创建启动对象
                    //        System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
                    //        startInfo.UseShellExecute = true;
                    //        startInfo.WorkingDirectory = Environment.CurrentDirectory;
                    //        startInfo.FileName = Application.ExecutablePath;
                    //        //设置启动动作,确保以管理员身份运行
                    //        startInfo.Verb = "runas";
                    //        try
                    //        {
                    //            System.Diagnostics.Process.Start(startInfo);
                    //        }
                    //        catch
                    //        {
                    //            return;
                    //        }
                    //        //退出
                    //        Application.Exit();
                    //    }

                    //}
                    //else
                    //{
                    //    ZhuCe();
                    //}
                }

                #endregion


                #endregion

            }


            #endregion

        }

        #region 异常捕获

        ///<summary>
        ///  这就是我们要在发生未处理异常时处理的方法，我这是写出错详细信息到文本，如出错后弹出一个漂亮的出错提示窗体，给大家做个参考
        ///  做法很多，可以是把出错详细信息记录到文本、数据库，发送出错邮件到作者信箱或出错后重新初始化等等
        ///  这就是仁者见仁智者见智，大家自己做了。
        ///</summary>
        ///<param name="sender"> </param>
        ///<param name="e"> </param>
        private static void Application_ThreadException(object sender, ThreadExceptionEventArgs e)
        {
            var ex = e.Exception;
            if (ex != null)
            {
                if (ex.Message.Length > 21 && ex.Message.Substring(0, 20).Contains("InvalidArgument="))
                {
                    NLogger.Default.Debug("ThreadException", ex.ToString());
                }
                else
                {
                    NLogger.Default.Debug("ThreadException", ex.ToString());
                    // OlivingMsg.Alert("系统出现未知异常:" + ex.ToString());
                    // MessageBox.Show("系统出现未知异常:" + ex.ToString());
                }
            }
        }

        private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            var ex = e.ExceptionObject as Exception;
            if (ex != null)
            {
                NLogger.Default.Debug("UnhandledException", ex.ToString());
                // OlivingLogTxt.writeLog(System.Windows.Forms.Application.StartupPath, "Log_CurrentDomain_UnhandledException", ex.ToString());
                // MessageBox.Show("系统出现未知异常:" + ex.ToString());
                // OlivingMsg.Alert("系统出现未知异常:" + ex.ToString()); 
            }
            //MessageBox.Show("系统出现未知异常，请重启系统！");
        }

        private static void OnApplicationExit(object sender, EventArgs e)
        {
            //stopListen();
        }
        #endregion

        public static void RunMain()
        {

            // Application.Run(new FormCameraTest());
            // Application.Run(new FormCalcImg());




            //    Application.Run(new  FormTest());
            Application.Run(new EMSClient.CForm.FormMain());

            //    Application.Run(new  FormWebBrowser());

            //if (1 == 2)
            //{
            //    Application.Run(new EMSClient.Form1());
            //}
            //else
            //{
            //    //如果是管理员，则直接运行
            //    if ((new FormLogin()).ShowDialog() == DialogResult.OK)
            //    {
            //        Application.Run(new EMSClient.CForm.FormMain());
            //    }
            //}
        }


        public static void ZhuCe()
        {

            #region 软件注册码

            string code = EmsConfigHelper.Regist; // ConfigHelper.GetValue("Regist");

            if (code.Length > 0)
            {
                #region 表示已注册，准确性检查
                try
                {
                    try
                    {
                        DateTime dt = new DateTime();

                        bool isBenji = Register.VerifyRegisterCode(Register.ReadMachineCode(), code, out dt);
                        if (isBenji)  //  是否与机器码进行绑定
                                      //  if (true)
                        {
                            if (DateTime.Now > dt)
                            {
                                MessageBox.Show("软件使用已到期,请重新注册该软件！", "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                                InputRegistCodeAndCheckIn();
                            }
                            else
                            {
                                RunMain();
                            }
                        }
                        else
                        {
                            MessageBox.Show("注册码错误，请确认您的注册是否有效！", "注册信息", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            InputRegistCodeAndCheckIn();
                        }
                    }
                    catch (Exception ee)
                    {
                        Splasher.Status = "正在初始化程序基础数据，注册码错误，请确认您的注册是否有效... ...";
                        MessageBox.Show("注册码错误，请确认您的注册是否有效！", "注册信息", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
                catch (Exception eee)
                {
                    Splasher.Status = "正在初始化程序基础数据，注册码错误，请确认您的注册是否有效... ...";
                    MessageBox.Show("注册码错误，请确认您的注册是否有效！", "注册信息", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                #endregion
            }
            else
            {
                Splasher.Status = "您的软件尚未注册，请联系您的系统采购商进行注册！";
                MessageBox.Show("您的软件尚未注册，请联系您的系统采购商进行注册！", "注册信息", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                if (new FrmRegist("Main").ShowDialog() == DialogResult.OK)
                {
                    RunMain();
                }
            }

            #endregion

        }

        /// <summary>
        /// 输入注册码并进行检测
        /// </summary>
        private static void InputRegistCodeAndCheckIn()
        {
            if (new FrmRegist("Main").ShowDialog() == DialogResult.OK)
            {
                RunMain();
            }
        }




    }
}
